package com.chen.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.annotation.OptLog;
import com.chen.common.OptTypeConst;
import com.chen.common.Result;
import com.chen.entity.Course;
import com.chen.entity.Exam;
import com.chen.entity.Sign;
import com.chen.entity.User;
import com.chen.mapper.ExamMapper;
import com.chen.mapper.UserMapper;
import com.chen.service.impl.ExamServiceImpl;
import com.chen.service.impl.SignServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author personcoder007
 * @since 2022-08-17
 */
@RestController
@RequestMapping("/exam")
@Api(value = "ExamController", tags = "考试管理")
public class ExamController {


    @Autowired
    private ExamServiceImpl examService;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SignServiceImpl signService;


    @PostMapping("/save")
    @ApiOperation(value = "新增或者更新")
    @OptLog(optType = OptTypeConst.SAVE_OR_UPDATE)
    public Result addDict(@RequestBody Exam exam) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = dateFormat.format(new Date());
        exam.setTime(format);
        Date date = new Date();

        examService.saveOrUpdate(exam);

        return Result.success();
    }


    //根据id进行删除
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除")
    @OptLog(optType = OptTypeConst.REMOVE)
    public Result deleteDict(@PathVariable("id") int id) {
        examService.removeById(id);
        return Result.success();
    }

    //批量删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "批量删除")
    @OptLog(optType = OptTypeConst.REMOVE_BATH)
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        examService.removeByIds(ids);

        return Result.success();
    }


    @RequestMapping("/page")
    @ApiOperation(value = "分页查询")
    public Result selectDict(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam(defaultValue = "") String name,
                             @RequestParam(defaultValue = "") String state) {


        return Result.success(examService.selectPage(pageNum, pageSize, name, state));
    }


    @RequestMapping(value = "findPage")
    @ApiOperation(value = "mybatis分页")
    public Result findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "5") Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {
        selectDoPaperIsDo();
        HashMap<String, Object> map = new HashMap<String, Object>();

        List<Exam> page = examService.findPage(pageNum, pageSize, name);
        map.put("page", page);
        map.put("count", examMapper.selectTotal(name));
        return Result.success(map);
    }

    @GetMapping(value = "selectExamDoing")
    @ApiOperation(value = "查询开始的开始")
    public Result selectExamDoing() {
        return Result.success(examMapper.selectExamDoing());
    }

    @GetMapping(value = "selectExam")
    @ApiOperation(value = "查询开始的开始")
    public Result selectExam() {
        return Result.success(examMapper.selectList(null));
    }

    @RequestMapping(value = "/findPage/front")
    @ApiOperation(value = "mybatis分页")
    public Result findPages(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "5") Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {
//        判断考试的当前状态
        selectDoPaperIsDo();

        QueryWrapper<Exam> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");
        if ((!"".equals(name))) {
            queryWrapper.like("name", name);
        }
        queryWrapper.ge("end_time",new Date());
        Page<Exam> page = examService.page(new Page<Exam>(pageNum, pageSize), queryWrapper);
        int loginId = StpUtil.getLoginIdAsInt();

        User user = userMapper.selectById(loginId);
        if (user.getRole().equals("ROLE_USER")) {
            queryWrapper.eq("user", user.getUsername());
        }
        List<Sign> signList = signService.list(new QueryWrapper<Sign>().eq("user_id", user.getId()));

        for (Exam record : page.getRecords()) {
            record.setEnable(false);
            Integer examId = record.getId();
            signList.stream().filter(s -> s.getExamId().equals(examId)).findFirst().ifPresent(s -> {
                record.setEnable("审核通过".equals(s.getState()));
            });
        }
        return Result.success(page);
    }


    @GetMapping("/selectExamById/{examId}")
    @ApiOperation(value = "根据id进行查询")
    public Result selectExamById(@PathVariable("examId") Integer examId) {
        return  Result.success(examService.getById(examId));

    }

    @GetMapping("/findAll")
    @ApiOperation(value = "根据id进行查询")
    public Result findAll() {
        return  Result.success(examService.list());
    }

    private void selectDoPaperIsDo(){
        List<Exam> examList = examMapper.selectList(null);
        for (Exam exam : examList) {
            Date date = new Date();

            UpdateWrapper<Exam> examUpdateWrapper = new UpdateWrapper<>();
            if (exam.getEndTime().getTime() < date.getTime()) {
                examUpdateWrapper.set("state", "已结束").eq("id", exam.getId());
                examService.update(examUpdateWrapper);
            }

            if (exam.getStartTime().getTime() > date.getTime()) {
                examUpdateWrapper.set("state", "未开始").eq("id", exam.getId());
                examService.update(examUpdateWrapper);
            }

            if (date.getTime() >= exam.getStartTime().getTime() && date.getTime() <= exam.getEndTime().getTime()) {
                examUpdateWrapper.set("state", "进行中").eq("id", exam.getId());
                examService.update(examUpdateWrapper);
            }
        }
    }
}

